package com.atom.module.mvvm.util

import android.app.Application
import kotlin.reflect.KClass

object Auto {

    private var app: Application? = null

    private val taskMap: MutableMap<KClass<*>, (Application) -> Boolean> = mutableMapOf()

    private val taskIgnore: MutableMap<KClass<*>, Boolean> = mutableMapOf()

    fun initAuto(app: Application) {
        this.app = app
    }

    /*task 返回默认为true 消费了 如果由于某些原因需要延时消费,返回false,但是最终的消费需要返回true 避免内存泄露*/
    fun registerTask(
        clazz: KClass<*>,
        task: (Application) -> Boolean
    ) {
        if (app == null) return
        if (taskIgnore[clazz] == true) {
            return
        }
        taskMap[clazz] = task
    }

    fun ignoreTask(clazz: KClass<*>) {
        if (app == null) return
        taskIgnore[clazz] = true
    }

    fun startTask(t: Any): Boolean {
        if (app == null) return false
        if (taskIgnore[t::class] == true) {
            return false
        }
        val get = taskMap[t::class] ?: return false
        if (get.invoke(app!!)) {
            taskMap.remove(t::class)
        }
        return true
    }
}
